package com.yeyaomai.dksns.flowis.servlet.dto;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yeyaomai.dksns.flowis.servlet.FlowUserController;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

@Repository
public class LoginInterceptor extends HandlerInterceptorAdapter {

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		HttpSession session = request.getSession(true);
		String username = request.getParameter("username");
		String param = request.getParameter("param");

		if(username !=null && param !=null) {
			String par = username+VelocityToolDateUtils.getDay(0);
			if(param.equals(FlowUserController.MD5(par))) {
				response.sendRedirect(request.getContextPath() + "/guest");
				return super.preHandle(request, response, handler);
			}
		}

		if(null == session.getAttribute("flowUser")){
			String[] noFilters = new String[] { "gif", "png", "ico", "jpg", "js","css", "/loginCheck","/addstoptime", "/toLogin","/getData", "/makeRandCode","/guest" };
			String url = request.getRequestURI();
			boolean beFilter = true;
			if (url.equals(getPath(request))) {
				beFilter = false;
			}
			for (String s : noFilters) {
				if (url.indexOf(s) != -1) {
					beFilter = false;
					break;
				}
			}
			if (beFilter) {
				if (null == session.getAttribute("flowUser")) {
					response.sendRedirect(request.getContextPath() + "/toLogin");
				}
			}
		} else {
			if(request.getRequestURI().equals("/flow/") || request.getRequestURI().equals("/")) {
				response.sendRedirect(request.getContextPath() + "/trend/today?time="+ VelocityToolDateUtils.getDay(0));
			}
		}
		return super.preHandle(request, response, handler);
	}

	private String getPath(HttpServletRequest request) {

		String path = request.getContextPath();
		if (path.equals("/")) {
			return "/";
		} else {
			return path + "/";
		}

	}
}
